//
//  AUSwapTitleView.swift
//  AwesomeUHomeModule_Example
//
//  Created by Miss_Special on 2018/4/16.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

import UIKit

import AwesomeUBaseModule

// MARK:- <定义常量>
/// 文字下边滚动条高度
private let swap_kScrollTitleLabelLineHeight: CGFloat = 2
/// titleView下边边线宽度
private let swap_kTitleViewBottomLineHeight: CGFloat = 0.5
/// label普通状态文字颜色
private let swap_kTitleLabelNormalRGB: (r: CGFloat, g: CGFloat, b: CGFloat) = (85, 85, 85)
/// label选中状态文字颜色
private let swap_kTitleLabelSelectedRGB: (r: CGFloat, g: CGFloat, b: CGFloat) = (255, 128, 0)
/// label颜色渐变的变化范围
private let swap_colorDelta: (r: CGFloat, g: CGFloat, b: CGFloat) = (
    swap_kTitleLabelSelectedRGB.r - swap_kTitleLabelNormalRGB.r,
    swap_kTitleLabelSelectedRGB.g - swap_kTitleLabelNormalRGB.g,
    swap_kTitleLabelSelectedRGB.b - swap_kTitleLabelNormalRGB.b
)

// MARK:- <协议 -> class 意味着只有类可以遵守该协议>
@objc public protocol AUSwapTitleViewDelegate: class {
    // 协议方法
    func swapTitleView(_ titleView: AUSwapTitleView, clickedIndex index: Int)
}

public class AUSwapTitleView: UIView {
    
    // MARK:- <Property - Normal>
    fileprivate var titles: [String]
    fileprivate var titleLabels: [UILabel] = [UILabel]()
    fileprivate var currentIndex: Int = 0
    // 代理要用weak修饰
    public weak var delegate: AUSwapTitleViewDelegate?
    
    // MARK:- <Property - Lazy>
    /// 滚动的titleView
    fileprivate lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false;
        /** 控制器中的ScrollView需要关闭这个属性, 才不会遮挡系统的点击顶部滚动到最上边的事件 **/
        scrollView.scrollsToTop = false;
        scrollView.bounces = false;
        
        return scrollView
    }()
    /// 滚动条
    fileprivate lazy var scrollLine: UIView = {
        let scrollLine = UIView()
        scrollLine.backgroundColor = UIColor.orange
        
        return scrollLine
    }()
    
    public init(frame: CGRect, titles: [String]) {
        
        self.titles = titles
        
        super.init(frame: frame)
        
        setupUI()
        
        backgroundColor = UIColor.white
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension AUSwapTitleView {
    /// 设置UI界面
    fileprivate func setupUI() {
        
        // 1. 添加scrollView
        addSubview(scrollView)
        scrollView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
        
        // 2. 添加Label
        createLabels()
        
        // 3. 添加滚动条和底部边线
        createBottomLineAndScrollLine()
    }
}

extension AUSwapTitleView {
    /// 给titleView添加标题
    fileprivate func createLabels() {
        let labelHeight: CGFloat = frame.size.height - swap_kTitleViewBottomLineHeight
        var fullWidth: CGFloat = 0
        for (index, title) in titles.enumerated() {
            // 创建label
            let label = UILabel()
            label.text = title
            
            label.sizeToFit()
            label.frame.size.height = labelHeight
            label.frame.size.width += 10
            
            label.textAlignment = NSTextAlignment.center
            label.textColor = UIColor(
                au_rgbColor: swap_kTitleLabelNormalRGB.r,
                g: swap_kTitleLabelNormalRGB.g,
                b: swap_kTitleLabelNormalRGB.b)
            label.tag = index
            
            // 添加到ScrollView中
            scrollView.addSubview(label)
            
            // 存储label
            titleLabels.append(label)
            
            // 给label添加手势
            label.isUserInteractionEnabled = true
            let gesture = UITapGestureRecognizer(target: self, action: #selector(self.titleClicked(_:)))
            label.addGestureRecognizer(gesture)
            
            fullWidth += label.frame.width
        }
        
        // 定位
        if fullWidth > au_kScreenWidth {
            for (index, label) in titleLabels.enumerated() {
                label.frame.origin.x = index > 0 ? titleLabels[index - 1].frame.maxX : 0
            }
            scrollView.contentSize = CGSize(width: fullWidth, height: 0)
            scrollView.bounces = true
        } else {
            let labelWidth: CGFloat = frame.size.width / CGFloat(titles.count)
            let labelY: CGFloat = 0
            for (index, label) in titleLabels.enumerated() {
                let labelX: CGFloat = labelWidth * CGFloat(index)
                label.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
            }
        }
    }
    
    /// 创建滚动条和底部边线
    fileprivate func createBottomLineAndScrollLine() {
        
        // 1. 创建滚动条
        guard let label = titleLabels.first else { return }
        label.textColor = UIColor.orange
        scrollLine.frame = CGRect(
            x: 0,
            y: frame.size.height - swap_kScrollTitleLabelLineHeight,
            width: label.frame.size.width,
            height: swap_kScrollTitleLabelLineHeight)
        scrollView.addSubview(scrollLine)
        
        // 2. 创建底部边线(添加在titleView中, 而不是在scrollView中, 不随scrollView滚动)
        let bottomLineFrame = CGRect(
            x: 0,
            y: frame.size.height - swap_kTitleViewBottomLineHeight,
            width: frame.size.width,
            height: swap_kTitleViewBottomLineHeight)
        let bottomLine = UIView(frame: bottomLineFrame)
        bottomLine.backgroundColor = UIColor.lightGray
        addSubview(bottomLine)
    }
}

// MARK:- <事件监听>
extension AUSwapTitleView {
    /// 标题点击
    @objc fileprivate func titleClicked(_ gesture: UIGestureRecognizer) {
        
        // 校验
        guard let label = gesture.view as? UILabel else {return}
        
        // 重复点击同一个title, 直接返回
        if label.tag == currentIndex {return}
        
        // 改变当前点击的label
        label.textColor = UIColor(
            au_rgbColor: swap_kTitleLabelSelectedRGB.r,
            g: swap_kTitleLabelSelectedRGB.g,
            b: swap_kTitleLabelSelectedRGB.b)
        
        // 改变上一个label
        let preLabel = titleLabels[currentIndex]
        preLabel.textColor = UIColor(
            au_rgbColor: swap_kTitleLabelNormalRGB.r,
            g: swap_kTitleLabelNormalRGB.g,
            b: swap_kTitleLabelNormalRGB.b)
        
        // 改变滚动条的位置
        let scrollLineX = label.frame.origin.x
        UIView.animate(withDuration: 0.15, animations: {
            self.scrollLine.frame.origin.x = scrollLineX
            self.scrollLine.frame.size.width = label.frame.width
        })
        
        // 记录当前的index
        currentIndex = label.tag
        
        // 将点击的索引传递给代理
        delegate?.swapTitleView(self, clickedIndex: currentIndex)
    }
}

// MARK:- <公共接口>
extension AUSwapTitleView {
    public func setProgress(_ progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
        // 取出label
        let sourceLabel = titleLabels[sourceIndex]
        let targetLabel = titleLabels[targetIndex]
        
        // 移动的总距离
        let moveMaxX: CGFloat = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
        
        // 移动的距离
        let moveX: CGFloat = moveMaxX * progress
        
        // 移动滑块
        scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
        
        // 改变颜色(渐变)
        sourceLabel.textColor = UIColor(
            au_rgbColor: swap_kTitleLabelSelectedRGB.r - swap_colorDelta.r * progress,
            g: swap_kTitleLabelSelectedRGB.g - swap_colorDelta.g * progress,
            b: swap_kTitleLabelSelectedRGB.b - swap_colorDelta.b * progress)
        targetLabel.textColor = UIColor(
            au_rgbColor: swap_kTitleLabelNormalRGB.r + swap_colorDelta.r * progress,
            g: swap_kTitleLabelNormalRGB.g + swap_colorDelta.g * progress,
            b: swap_kTitleLabelNormalRGB.b + swap_colorDelta.b * progress)
        
        // 记录当前的index
        currentIndex = targetIndex
    }
}
